package com.laike.pay.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;

import com.laike.pay.http.HttpRetrofit;
import com.laike.pay.http.api.SerivceApi;
import com.laike.pay.utils.GreenDaoManager;
import com.iflytek.cloud.SpeechUtility;
import com.pax.pay.service.aidl.PayHelper;

import java.util.Stack;

public class MyApplication extends Application {
    private static Context instance = null;
    private Stack<Activity> mActivitys;
    protected static MyApplication mApp;

    @Override
    public void onCreate() {
        mApp = this;
        newActivityStack();
        //应用程序入口处调用，避免手机内存过小，杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
        // 如在Application中调用初始化，需要在Mainifest中注册该Applicaiton
        // 注意：此接口在非主进程调用会返回null对象，如需在非主进程使用语音功能，请增加参数：SpeechConstant.FORCE_LOGIN+"=true"
        // 参数间使用半角“,”分隔。
        // 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符

        // 注意： appid 必须和下载的SDK保持一致，否则会出现10407错误

        SpeechUtility.createUtility(MyApplication.this, "appid=5aa643fc");

        // 以下语句用于设置日志开关（默认开启），设置成false时关闭语音云SDK日志打印
        // Setting.setShowLog(false);
        super.onCreate();
        instance = getApplicationContext();
        GreenDaoManager.getInstance();
    }

    /**
     * 创建activity栈
     */
    private void newActivityStack() {
        if (mActivitys == null) {
            mActivitys = new Stack<Activity>();
        }
    }

    /**
     * 添加一个activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (!mActivitys.contains(activity)) {
            mActivitys.add(activity);
        }
    }


    /**
     * 获取application实例
     *
     * @return
     */
    public static MyApplication getApp() {
        return mApp;
    }

    /**
     * 结束所有activity
     */
    private void finishAllActivity() {
        while (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

    /**
     * 退出application
     */
    public void exitApplication() {
        exitApplication(true);
    }

    public void exitApplication(boolean needbackground) {
        finishAllActivity();
        if (!needbackground) {
            System.exit(0);
        }
    }

    public static Context getContext() {
        return instance.getApplicationContext();
    }

    public static SerivceApi getSerivceApi() {
        return HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class);
    }
}
